package com.example.pt.service.impl;

import com.example.pt.entity.Notification;
import com.example.pt.entity.Post;
import com.example.pt.entity.Reply;
import com.example.pt.entity.User;
import com.example.pt.repository.PostRepository;
import com.example.pt.repository.ReplyRepository;
import com.example.pt.repository.UserRepository;
import com.example.pt.service.NotificationService;
import com.example.pt.service.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class ReplyServiceImpl implements ReplyService {

    @Autowired
    private ReplyRepository replyRepository;

    @Autowired
    private PostRepository postRepository;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private NotificationService notificationService;

    @Override
    public Reply createReply(Reply reply) {
        reply.setCreated_at(LocalDateTime.now());
        // 查询用户名并设置
        if (reply.getUser_id() != null) {
            Optional<User> userOptional = userRepository.findById(reply.getUser_id());
            userOptional.ifPresent(user -> reply.setUsername(user.getUsername()));
        }
        replyRepository.save(reply);

        Optional<Post> postOptional = postRepository.findById(reply.getPost_id());
        if (postOptional.isPresent()) {
            Post post = postOptional.get();
            Long authorId = post.getUser_id() == null ? null : post.getUser_id().longValue();
            Long replierId = reply.getUser_id() == null ? null : reply.getUser_id().longValue();

            // 不给自己发通知
            if (authorId != null && !authorId.equals(replierId)) {
                Notification notification = new Notification();
                notification.setUser_id(authorId);
                //String url = "http://192.168.43.26/posts/" + post.getPost_id() + "/replies";
                notification.setTitle("你的帖子有新回复");
                notification.setContent("你的帖子《" + post.getTitle() + "》收到一条新评论。\n点击查看：" );

                notification.setCreate_time(LocalDateTime.now());
                notification.setStatus(0);


                notificationService.createNotification(notification);
            }
        }

        return reply;
    }
}
